package listbyorder.access201_300.test297;

import listbyorder.utils.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author code_yc
 * @version 1.0
 * @date 2020/6/28 16:38
 */
// 方法二 ： 使用前序遍历的方法进行序列化
public class Codec2 {

    // Encodes a tree to a single string.
    // 递归实现
    public String serialize(TreeNode root) {
        if (root == null) return "#!";
        String res = root.val + "!";
        res += serialize(root.left);
        res += serialize(root.right);
        return res;
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        String[] split = data.split("!");
        Queue<String> queue = new LinkedList<>();
        for (String s : split) {
            queue.add(s);
        }
        return getTree(queue);
    }

    private TreeNode getTree(Queue<String> queue) {
        String str = queue.poll();
        if (str.equals("#")) {
            return null;
        }
        TreeNode root = new TreeNode(Integer.parseInt(str));
        root.left = getTree(queue);
        root.right = getTree(queue);
        return root;
    }
}
